package com.herench.bridge.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.herench.bridge.SmsService;
import com.herench.bridge.StrangeMessage;
import com.herench.bridge.utils.DesUtil;
import com.herench.bridge.utils.HttpClientSupport;
import com.herench.bs.utils.IdGenerator;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 短信消息发送
 * Created by ThinkPad on 2017/9/22.
 */

@Component("smsService")
@javax.jws.WebService(endpointInterface = "com.herench.bridge.SmsService", serviceName = "smsService", targetNamespace = "http://bridge.herench.com/")
public class SmsServiceImpl implements SmsService {

    private static final Logger logger = Logger.getLogger(SmsServiceImpl.class);

    @Value("${smsUrl}")
    private String smsUrl;

    @Override
    public String sendSms(String message) {
        logger.info("request:" + message);
        StrangeMessage responseMessage = new StrangeMessage();
        responseMessage.addAttrToClientInfo("METHOD", "sendSms");
        try {
            StrangeMessage requestMessage = new StrangeMessage(message);
            String sysCode = requestMessage.getAttrFromClientInfo("OPT_ID");
            Assert.hasLength(sysCode, "OPT_ID 为空");
            String phone = requestMessage.getAttrFromCommitDataRow("PHONE");
            Assert.hasLength(phone, "PHONE 为空");
            String sign = requestMessage.getAttrFromCommitDataRow("SIGN");
            String method = requestMessage.getAttrFromClientInfo("METHOD");
            Map<String, Object> params = new HashMap<>();
            String vcode = IdGenerator.getSixRandNum();
            params.put("sysCode", sysCode);
            params.put("phone", phone);
            params.put("vcode", vcode);
            params.put("sign", sign);
            if (method.startsWith("57")) {
                String deptName = requestMessage.getAttrFromCommitDataRow("DEPT_NAME");
                String docName = requestMessage.getAttrFromCommitDataRow("DOC_NAME");
                String timeString = requestMessage.getAttrFromCommitDataRow("TIME_STRING");
                String period = requestMessage.getAttrFromCommitDataRow("PERIOD");
                String name = requestMessage.getAttrFromCommitDataRow("NAME");
                String itemName = requestMessage.getAttrFromCommitDataRow("ITEM_NAME");
                String staffName = requestMessage.getAttrFromCommitDataRow("STAFF_NAME");

                if (StringUtils.hasLength(deptName)) {
                    params.put("deptName", deptName);
                }
                if (StringUtils.hasLength(docName)) {
                    params.put("docName", docName);
                }
                if (StringUtils.hasLength(timeString)) {
                    params.put("timeString", timeString);
                }
                if (StringUtils.hasLength(period)) {
                    params.put("period", period);
                }
                if (StringUtils.hasLength(name)) {
                    params.put("name", name);
                }
                if (StringUtils.hasLength(staffName)) {
                    params.put("staffName", staffName);
                }
                if (StringUtils.hasLength(itemName)) {
                    params.put("itemName", itemName);
                }


            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("funcode", method);
            jsonObject.put("token", "token");
            jsonObject.put("args", DesUtil.encrypt(JSON.toJSONString(params)));
            String tempMsg = jsonObject.toString();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String str = null;
                    try {
                        str = HttpClientSupport.doPost(smsUrl, tempMsg, "UTF-8");
                        logger.info("调用auth返回:" + str);
                    } catch (Exception e) {
                        logger.info("调用第一次请求异常信息:" + str);
                        str = null;
                        try {
                            str = HttpClientSupport.doPost(smsUrl, tempMsg, "UTF-8");
                        } catch (Exception e1) {
                            logger.info("第二次请求异常信息:" + str);
                            try {
                                str = HttpClientSupport.doPost(smsUrl, tempMsg, "UTF-8");
                            } catch (Exception e2) {
                                e2.printStackTrace();
                                logger.info("第三次请求异常信息:" + str);
                            }
                            e1.printStackTrace();
                        }
                        e.printStackTrace();
                    }

                }
            }).start();
            responseMessage.addExecuteStatus("0");
            responseMessage.addExecuteMessage("短信发送成功");
            responseMessage.addAttrToReturnData("vcode", vcode);
            responseMessage.addAttrToReturnData("phone", phone);
        } catch (Exception e) {
            responseMessage.addExecuteStatus("1");
            if (e.getMessage() == null) {
                responseMessage.addExecuteMessage("请求超时，请重试！");
            } else {
                responseMessage.addExecuteMessage(e.getMessage());
            }
            logger.info("异常信息：" + e.getCause());
            e.printStackTrace();
        }
        logger.info("response:" + responseMessage);
        return responseMessage.getBody().asXML();
    }

    @Override
    public String validate(String message) {
        logger.info("request:" + message);
        StrangeMessage responseMessage = new StrangeMessage();
        responseMessage.addAttrToClientInfo("METHOD", "validate");
        try {
            StrangeMessage requestMessage = new StrangeMessage(message);
            String sysCode = requestMessage.getAttrFromClientInfo("OPT_ID");
            Assert.hasLength(sysCode, "OPT_ID 为空");
            String phone = requestMessage.getAttrFromCommitDataRow("PHONE");
            Assert.hasLength(phone, "PHONE 为空");
            String vcode = requestMessage.getAttrFromCommitDataRow("VCODE");
            Assert.hasLength(phone, "VCODE 为空");
            String sign = requestMessage.getAttrFromCommitDataRow("SIGN");
            Map<String, Object> params = new HashMap<>();
            params.put("sysCode", sysCode);
            params.put("phone", phone);
            params.put("vcode", vcode);
            params.put("sign", sign);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("funcode", "500101");
            jsonObject.put("token", "token");
            jsonObject.put("args", DesUtil.encrypt(JSON.toJSONString(params)));
            String str = HttpClientSupport.doPost(smsUrl, jsonObject.toString(), "UTF-8");
            JSONObject resJson = JSON.parseObject(str);
            responseMessage.addExecuteStatus(resJson.getString("code"));
            responseMessage.addExecuteMessage(resJson.getString("message"));
        } catch (Exception e) {
            responseMessage.addExecuteStatus("1");
            if (e.getMessage() == null) {
                responseMessage.addExecuteMessage("请求超时，请重试！");
            } else {
                responseMessage.addExecuteMessage(e.getMessage());
            }
            logger.info("异常信息:" + e.getCause());
            e.printStackTrace();
        }
        logger.info("response:" + responseMessage);
        return responseMessage.getBody().asXML();
    }

    @Override
    public String weChat(String message) {
        logger.info("request:" + message);
        StrangeMessage responseMessage = new StrangeMessage();
        responseMessage.addAttrToClientInfo("METHOD", "weChat");
        try {
            StrangeMessage requestMessage = new StrangeMessage(message);
            String sysCode = requestMessage.getAttrFromClientInfo("OPT_ID");
            Assert.hasLength(sysCode, "OPT_ID 为空");
            String phone = requestMessage.getAttrFromCommitDataRow("PHONE");
            Assert.hasLength(phone, "PHONE 为空");
            String sign = requestMessage.getAttrFromCommitDataRow("SIGN");
            String method = requestMessage.getAttrFromClientInfo("METHOD");
            Map<String, Object> params = new HashMap<>();
            String vcode = IdGenerator.getSixRandNum();
            params.put("sysCode", sysCode);
            params.put("phone", phone);
            params.put("vcode", vcode);
            params.put("sign", sign);
            if (method.startsWith("500")) {
                String deptName = requestMessage.getAttrFromCommitDataRow("DEPT_NAME");
                String docName = requestMessage.getAttrFromCommitDataRow("DOC_NAME");
                String timeString = requestMessage.getAttrFromCommitDataRow("TIME_STRING");
                String period = requestMessage.getAttrFromCommitDataRow("PERIOD");
                String hospital = requestMessage.getAttrFromCommitDataRow("HOSPITAL");
                String name = requestMessage.getAttrFromCommitDataRow("NAME");
                String itemName = requestMessage.getAttrFromCommitDataRow("ITEM_NAME");
                String staffName = requestMessage.getAttrFromCommitDataRow("STAFF_NAME");
                String headerTitle = requestMessage.getAttrFromCommitDataRow("HEADER_TITLE");
                String remark = requestMessage.getAttrFromCommitDataRow("REMARK");
                String dateString = requestMessage.getAttrFromCommitDataRow("DATE_STRING");
                String visitNo = requestMessage.getAttrFromCommitDataRow("VISIT_NO");
                String callNo = requestMessage.getAttrFromCommitDataRow("CALL_NO");
                String customer = requestMessage.getAttrFromCommitDataRow("CUSTOMER");
                String orderId = requestMessage.getAttrFromCommitDataRow("ORDID");
                String money = requestMessage.getAttrFromCommitDataRow("MONEY");
                String payTime = requestMessage.getAttrFromCommitDataRow("PAY_TIME");
                String itemTime = requestMessage.getAttrFromCommitDataRow("ITEM_TIME");
                String dagItem = requestMessage.getAttrFromCommitDataRow("DAG_ITEM");
                String dagResult = requestMessage.getAttrFromCommitDataRow("DAG_RESULT");

                if (StringUtils.hasLength(deptName)) {
                    params.put("deptName", deptName);
                }
                if (StringUtils.hasLength(docName)) {
                    params.put("docName", docName);
                }
                if (StringUtils.hasLength(timeString)) {
                    params.put("timeString", timeString);
                }
                if (StringUtils.hasLength(period)) {
                    params.put("period", period);
                }
                if (StringUtils.hasLength(name)) {
                    params.put("name", name);
                }
                if (StringUtils.hasLength(staffName)) {
                    params.put("staffName", staffName);
                }
                if (StringUtils.hasLength(itemName)) {
                    params.put("itemName", itemName);
                }
                if (StringUtils.hasLength(hospital)) {
                    params.put("hospital", hospital);
                }
                if (StringUtils.hasLength(headerTitle)) {
                    params.put("headerTitle", headerTitle);
                }
                if (StringUtils.hasLength(remark)) {
                    params.put("remark", remark);
                }
                if (StringUtils.hasLength(dateString)) {
                    params.put("dateString", dateString);
                }
                if (StringUtils.hasLength(visitNo)) {
                    params.put("visitNo", visitNo);
                }
                if (StringUtils.hasLength(callNo)) {
                    params.put("callNo", callNo);
                }
                if (StringUtils.hasLength(customer)) {
                    params.put("customer", customer);
                }
                if (StringUtils.hasLength(orderId)) {
                    params.put("orderId", orderId);
                }
                if (StringUtils.hasLength(money)) {
                    params.put("money", money);
                }
                if (StringUtils.hasLength(payTime)) {
                    params.put("payTime", payTime);
                }
                if (StringUtils.hasLength(itemTime)) {
                    params.put("itemTime", itemTime);
                }
                if (StringUtils.hasLength(dagItem)) {
                    params.put("dagItem", dagItem);
                }
                if (StringUtils.hasLength(dagResult)) {
                    params.put("dagResult", dagResult);
                }
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("funcode", method);
            jsonObject.put("token", "token");
            jsonObject.put("args", DesUtil.encrypt(JSON.toJSONString(params)));
            String tempMsg = jsonObject.toString();
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    String str = null;
//                    try {
//                        str = HttpClientSupport.doPost(smsUrl, tempMsg, "UTF-8");
//                        logger.info("调用auth返回:" + str);
//                    } catch (Exception e) {
//                        logger.info("调用第一次请求异常信息:" + str);
//                        str = null;
//                        try {
//                            str = HttpClientSupport.doPost(smsUrl, tempMsg, "UTF-8");
//                        } catch (Exception e1) {
//                            logger.info("第二次请求异常信息:" + str);
//                            try {
//                                str = HttpClientSupport.doPost(smsUrl, tempMsg, "UTF-8");
//                            } catch (Exception e2) {
//                                e2.printStackTrace();
//                                logger.info("第三次请求异常信息:" + str);
//                            }
//                            e1.printStackTrace();
//                        }
//                        e.printStackTrace();
//                    }
//
//                }
//            }).start();
            responseMessage.addExecuteStatus("0");
            responseMessage.addExecuteMessage("微信消息发送成功");
            responseMessage.addAttrToReturnData("phone", phone);
        } catch (Exception e) {
            responseMessage.addExecuteStatus("1");
            if (e.getMessage() == null) {
                responseMessage.addExecuteMessage("请求超时，请重试！");
            } else {
                responseMessage.addExecuteMessage(e.getMessage());
            }
            logger.info("异常信息：" + e.getCause());
            e.printStackTrace();
        }
        logger.info("response:" + responseMessage);
        return responseMessage.getBody().asXML();
    }

}
